/*
//  Copyright © 2014 Allen County Public Library.

  //        ACPL Mobile is free software: This program is distributed and you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.  ACPL Mobile is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, including without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ACPL Mobile. If not, see http://www.gnu.org/licenses/.
 * Author: James Harpe
 * 
 * 
 * Description: This activity displays detailed information about a catalog title. 
 */

package us.in.lib.acpl.Mobile_ACPL;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.text.WordUtils;

import com.google.analytics.tracking.android.EasyTracker;


import us.in.lib.acpl.Mobile_ACPL.context.Mobile_ACPL;
import us.in.lib.acpl.Mobile_ACPL.item.AvailabilityInfo;
import us.in.lib.acpl.Mobile_ACPL.item.CallInfo;
import us.in.lib.acpl.Mobile_ACPL.location.LocationInfo;
import us.in.lib.acpl.Mobile_ACPL.parents.BaseActivity;

import us.in.lib.acpl.Mobile_ACPL.ws.ItemDetailHandler;
import us.in.lib.acpl.Mobile_ACPL.ws.MoreAuthorSearchHandler;
import us.in.lib.acpl.Mobile_ACPL.ws.PlaceHoldHandler;
import us.in.lib.acpl.Mobile_ACPL.ws.SearchCatalogHandler;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class SearchResultsTitleDetailActivity extends BaseActivity {
    //ACPL: Removed ACPL specific Sirsi Web Services and Syndetics URLs
	public static final String WS_URL = "http://sws.acpl.lib.in.us:8080/symws/rest/standard/lookupTitleInfo";
	public static final String URL_START = "http://www.syndetics.com/index.aspx?isbn=";
	public static final String IMAGE_URL_END = "/mc.gif&upc=&oclc=&client=260-421-1200";
	public static final String IMAGE_LARGE_URL_END = "/lc.gif&upc=&oclc=&client=260-421-1200";
	public static final String SUMMARY_URL_END = "/summary.xml&client=260-421-1200";
	public static final String AUTHOR_NOTES_URL_END = "/anotes.xml&client=260-421-1200";
	public static final String LJ_REVIEW_URL_END = "/ljreview.xml&client=260-421-1200";
	public static final String PW_REVIEW_URL_END = "/pwreview.xml&client=260-421-1200";
	public static final int LOGIN = 0;
	private String pickupLibrary = null;

	private SearchResultsTitleDetailActivity thisActivity = this;
	private boolean availShown = false;
	private boolean availFetched = false;

	private boolean summaryShown = false;
	private boolean summaryFetched = false;

	private boolean authorNotesShown = false;
	private boolean authorNotesFetched = false;

	private ItemDetailHandler handler;
	
	String isbn;
	String titleID;
	String title;
	String author;
	String materialType;
	boolean holdable;
	String yearOfPublication;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		this.getActionBar().setTitle("  Title Details");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_title_detail);

		isbn = getIntent().getStringArrayExtra("isbn")[0];
		titleID = getIntent().getStringExtra("titleID");
		title = getIntent().getStringExtra("title");
		author = getIntent().getStringExtra("author");
		materialType = getIntent().getStringExtra("materialType");
		holdable = getIntent().getBooleanExtra("holdable",false);
		yearOfPublication = getIntent().getStringExtra("yearOfPublication");
		handler = new ItemDetailHandler(this, isbn, titleID, title, author,
				materialType);

		// set listeners
		setListeners();
		displayInfo();

		displayButtons();

	}
	  @Override
	  public void onStart() {
	    super.onStart();
	    EasyTracker.getInstance().activityStart(this); // Add this method.
	  }

	  @Override
	  public void onStop() {
	    super.onStop();
	    EasyTracker.getInstance().activityStop(this); // Add this method.
	  }
	public void setListeners() {

		findViewById(R.id.summary).setOnClickListener(new SummaryListener());
		findViewById(R.id.availabilityLayout).setOnClickListener(
				new AvailabilityListener());
		findViewById(R.id.summaryContent).setOnClickListener(
				new SummaryListener());
		findViewById(R.id.placeHold).setOnClickListener(new HoldListener());
		findViewById(R.id.authorNotes).setOnClickListener(
				new AuthorNotesListener());
		findViewById(R.id.authorNotesContent).setOnClickListener(
				new AuthorNotesListener());
		findViewById(R.id.authorNotesLayout).setOnClickListener(
				new AuthorNotesListener());

		findViewById(R.id.moreAuthor).setOnClickListener(
				new MoreAuthorListener());
		findViewById(R.id.overdriveLink).setOnClickListener(
				new OverdriveListener());
		findViewById(R.id.addToListButton).setOnClickListener(new AddToListListener());

	}

	public void displayInfo() {
		handler.getCoverImage();
		TextView t = (TextView) this.findViewById(R.id.title);
		t.setText(this.getIntent().getStringExtra("title"));

		t = (TextView) this.findViewById(R.id.author);
		t.setText(this.getIntent().getStringExtra("author"));

		t = (TextView) this.findViewById(R.id.year);
		t.setText(this.getIntent().getStringExtra("yearOfPublication"));

		t = (TextView) this.findViewById(R.id.summary);
		t.setText("Summary");

		t = (TextView) this.findViewById(R.id.itemAvailabilityInfo);
		t.setText("Item Availability");

		t = (TextView) this.findViewById(R.id.authorNotes);
		t.setText("Author Notes");

	}

	public void displayItemAvailabilityInfo(List<AvailabilityInfo> list) {

		// Remove the progress bar
		View v = findViewById(R.id.availBar);
		v.setVisibility(View.GONE);

		LinearLayout layout = (LinearLayout) this
				.findViewById(R.id.availabilityTables);

		for (AvailabilityInfo avail : list) {
			TableLayout table = new TableLayout(this);
			table.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
					LayoutParams.MATCH_PARENT));
			table.setStretchAllColumns(true);
			table.setPadding(0, 5, 0, 5);
			TableRow tr = new TableRow(this);
			tr.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
					LayoutParams.MATCH_PARENT));

			TextView tv = new TextView(this);
			String library = avail.getLibrary();
			library = library.toLowerCase();
			library = library.replace("_", " ");

			library = WordUtils.capitalize(library);
			library = library.replace("Hsn", "Hessen");
			library = library.replace("Ltl", "Little");
			library = library.replace("Mnroeville", "Monroeville");
			tv.setText(library);
			tv.setWidth((int) TypedValue.applyDimension(
					TypedValue.COMPLEX_UNIT_DIP, 65, getResources()
							.getDisplayMetrics()));
			tv.setTextSize(15);
			tv.setTextColor(Color.BLACK);
			tr.addView(tv, new TableRow.LayoutParams(0));

			tv = new TextView(this);
			tv.setText("# of Copies");
			tv.setWidth((int) TypedValue.applyDimension(
					TypedValue.COMPLEX_UNIT_DIP, 45, getResources()
							.getDisplayMetrics()));
			tv.setTextColor(Color.BLACK);
			tv.setGravity(Gravity.CENTER_HORIZONTAL);
			tv.setTextSize(15);
			tr.addView(tv, new TableRow.LayoutParams(0));

			tv = new TextView(this);
			tv.setText("Location");
			tv.setGravity(Gravity.CENTER_HORIZONTAL);
			tv.setWidth((int) TypedValue.applyDimension(
					TypedValue.COMPLEX_UNIT_DIP, 50, getResources()
							.getDisplayMetrics()));
			tv.setTextSize(15);
			tv.setTextColor(Color.BLACK);
			tr.addView(tv, new TableRow.LayoutParams(0));
			tr.setPadding(0, 0, 0, 5);
			table.addView(tr);

			List<CallInfo> callValues = avail.getCallInfo();
			for (CallInfo curr : callValues) {
				HashMap<String, Integer> map = curr.getCopyLocations();
				int iter = 0;
				for (Map.Entry<String, Integer> currLoc : map.entrySet()) {
					String loc = currLoc.getKey();
					String num = "" + currLoc.getValue();

					tr = new TableRow(this);
					tr.setLayoutParams(new LayoutParams(
							LayoutParams.MATCH_PARENT,
							LayoutParams.MATCH_PARENT));

					if (iter == 0) {

						tv = new TextView(this);
						tv.setText(curr.getCallNumber());

						tv.setTextSize(13);
						tv.setTextColor(Color.GRAY);
						tv.setWidth((int) TypedValue.applyDimension(
								TypedValue.COMPLEX_UNIT_DIP, 70, getResources()
										.getDisplayMetrics()));

						tr.addView(tv, new TableRow.LayoutParams(0));
					} else {
						tv = new TextView(this);

						tv.setWidth((int) TypedValue.applyDimension(
								TypedValue.COMPLEX_UNIT_DIP, 70, getResources()
										.getDisplayMetrics()));
						tv.setTextColor(Color.GRAY);
						tr.addView(tv, new TableRow.LayoutParams(0));
					}

					tv = new TextView(this);
					tv.setWidth((int) TypedValue.applyDimension(
							TypedValue.COMPLEX_UNIT_DIP, 40, getResources()
									.getDisplayMetrics()));
					tv.setTextSize(13);
					tv.setTextColor(Color.GRAY);
					tv.setText(num);
					tv.setGravity(Gravity.CENTER_HORIZONTAL);

					tr.addView(tv, new TableRow.LayoutParams(0));

					tv = new TextView(this);
					tv.setWidth((int) TypedValue.applyDimension(
							TypedValue.COMPLEX_UNIT_DIP, 50, getResources()
									.getDisplayMetrics()));
					tv.setTextSize(13);
					tv.setTextColor(Color.GRAY);
					tv.setText(loc);
					tv.setGravity(Gravity.CENTER_HORIZONTAL);

					tr.addView(tv, new TableRow.LayoutParams(0));

					table.addView(tr);

					iter++;
				}
			}

			View line = new View(this);
			line.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 1));
			line.setBackgroundColor(Color.parseColor("#888888"));

			layout.addView(line);

			layout.addView(table);

			layout.setVisibility(View.VISIBLE);

		}

	}

	public void displayButtons() {

		boolean holdable = getIntent().getBooleanExtra("holdable", false);

		if (holdable) {
			View v = findViewById(R.id.placeHold);

			v.setVisibility(View.VISIBLE);
		}

		String author = getIntent().getStringExtra("author");
		if ((!author.equalsIgnoreCase("")) && author != null) {

			findViewById(R.id.moreAuthor).setVisibility(View.VISIBLE);
		}

		String url = getIntent().getStringExtra("url");
		if (url != null && !url.equals("")) {
			findViewById(R.id.overdriveLink).setVisibility(View.VISIBLE);
		}

	}

	public void setImage(Bitmap image) {

		View v = findViewById(R.id.coverBar);
		v.setVisibility(View.GONE);

		ImageView iv = (ImageView) findViewById(R.id.coverImage);

		if (image == null || image.getHeight() <= 1) {
			String type = getIntent().getStringExtra("materialType");
			if (type.equalsIgnoreCase("Book") || type.equalsIgnoreCase("CR")
					|| type.equalsIgnoreCase("Music")) {

				iv.setImageResource(R.drawable.book);

			} else if (type.equalsIgnoreCase("Sounddisc")
					|| type.equalsIgnoreCase("SOUNDCASS")) {
				
				iv.setImageResource(R.drawable.music);
				
			} else if (type.equalsIgnoreCase("VIDEODISC")
					|| type.equalsIgnoreCase("VIDEOCASS")
					|| type.equalsIgnoreCase("VISUALS")) {
				
				iv.setImageResource(R.drawable.video);

			} else {
				iv.setImageResource(R.drawable.misc);
				
				
				
			}

		} else {
			iv.setImageBitmap(image);
			iv.setOnClickListener(new ImageListener());
			
			ImageView icon =(ImageView) this.findViewById(R.id.materialIcon);
			icon.setVisibility(View.VISIBLE);
			String type = getIntent().getStringExtra("materialType");
			if (type.equalsIgnoreCase("Book") || type.equalsIgnoreCase("CR")
					|| type.equalsIgnoreCase("Music")) {

				icon.setImageResource(R.drawable.book);

			} else if (type.equalsIgnoreCase("Sounddisc")
					|| type.equalsIgnoreCase("SOUNDCASS")) {
				
				icon.setImageResource(R.drawable.music);
				
			} else if (type.equalsIgnoreCase("VIDEODISC")
					|| type.equalsIgnoreCase("VIDEOCASS")
					|| type.equalsIgnoreCase("VISUALS")) {
				
				icon.setImageResource(R.drawable.video);

			} else {
				icon.setImageResource(R.drawable.misc);
			}
			
		}
		iv.setVisibility(View.VISIBLE);
	}

	public void setSummaryText(String summary) {

		View v = findViewById(R.id.bar);
		v.setVisibility(View.GONE);

		TextView summaryContent = (TextView) findViewById(R.id.summaryContent);
		summaryContent.setText(summary);
		summaryContent.setVisibility(View.VISIBLE);

	}

	public void setAuthorNotes(String authorNotes) {

		View v = findViewById(R.id.authorNotesBar);
		v.setVisibility(View.GONE);

		TextView authorNotesContent = (TextView) findViewById(R.id.authorNotesContent);
		authorNotesContent.setText(authorNotes);
		authorNotesContent.setVisibility(View.VISIBLE);

	}

	public void handleHoldResult(boolean success, String failureReason) {

		findViewById(R.id.holdBar).setVisibility(View.GONE);
		String message;

		if (success) {
			message = "Hold placed!";
		
		
			EasyTracker.getTracker().sendEvent("Search", "Hold Placed", null, null);
		} else {

			EasyTracker.getTracker().sendEvent("Search", "Hold Placement Failed", null, null);
			
			message = failureReason;
		}
		Toast toast = Toast.makeText(this.getBaseContext(), message,
				Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}

	public void showHoldDialog() {

		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("Select Pickup Library");
		RelativeLayout layout = (RelativeLayout) this.getLayoutInflater()
				.inflate(R.layout.place_hold, null);
		alert.setView(layout);

		Spinner spinner = (Spinner) layout
				.findViewById(R.id.pickupLibrarySelector);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.libraryLocations,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View view,
					int arg2, long arg3) {
				if (view != null) {
					TextView t = (TextView) view;
					String text = (String) t.getText();
					pickupLibrary = LocationInfo.getSystemName(text);

				}

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}

		});

		alert.setPositiveButton("Place Hold",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int whichButton) {

						dialog.dismiss();

						findViewById(R.id.holdBar).setVisibility(View.VISIBLE);
						PlaceHoldHandler handler = new PlaceHoldHandler(
								thisActivity);
						handler.placeHold(
								getIntent().getStringExtra("titleID"),
								pickupLibrary);

					}
				});

		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int whichButton) {

						dialog.dismiss();
					}
				});

		alert.show();

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == RESULT_OK) {

			showHoldDialog();
		}

	}

	private class SummaryListener implements OnClickListener {

		@Override
		public void onClick(View view) {
			int id = view.getId();

			switch (id) {

			case R.id.summary:
			case R.id.summaryContent:
				if (!summaryShown) {


					EasyTracker.getTracker().sendEvent("Search", "Summary Pressed", null, null);
					summaryShown = true;

					if (!summaryFetched) {
						// Create a progress bar to display during the operation
						summaryFetched = true;
						View v = findViewById(R.id.bar);
						v.setVisibility(View.VISIBLE);
						handler.getSummary();
					} else {
						TextView t = (TextView) findViewById(R.id.summaryContent);
						t.setVisibility(View.VISIBLE);
					}
				} else {

					summaryShown = false;
					TextView t = (TextView) findViewById(R.id.summaryContent);
					t.setVisibility(View.GONE);

				}
				break;

			}

		}

	}

	private class AvailabilityListener implements OnClickListener {

		@Override
		public void onClick(View view) {

			if (!availShown) {

				Activity act = (Activity)view.getContext();

				EasyTracker.getTracker().sendEvent("Search", "Item Availability Pressed", null, null);
				
				availShown = true;
				if (!availFetched) {
					// Create a progress bar to display during the operation
					availFetched = true;

					// Start a task in a new thread to get the avail
					View v = findViewById(R.id.availBar);
					v.setVisibility(View.VISIBLE);
					handler.getItemAvailabilityInfo();
				} else {
					LinearLayout layout = (LinearLayout) findViewById(R.id.availabilityTables);
					layout.setVisibility(View.VISIBLE);
				}
			} else {

				availShown = false;
				LinearLayout layout = (LinearLayout) findViewById(R.id.availabilityTables);
				layout.setVisibility(View.GONE);

			}

		}

	}

	private class AuthorNotesListener implements OnClickListener {

		@Override
		public void onClick(View view) {

			if (!authorNotesShown) {



				EasyTracker.getTracker().sendEvent("Search", "Author Notes Pressed", null, null);
				
				authorNotesShown = true;
				if (!authorNotesFetched) {
					// Create a progress bar to display during the operation
					authorNotesFetched = true;

					// Start a task in a new thread to get the avail
					View v = findViewById(R.id.authorNotesBar);
					v.setVisibility(View.VISIBLE);
					handler.getAuthorNotes();
				} else {
					View v = findViewById(R.id.authorNotesContent);
					v.setVisibility(View.VISIBLE);
				}
			} else {

				authorNotesShown = false;
				View v = findViewById(R.id.authorNotesContent);
				v.setVisibility(View.GONE);

			}

		}

	}

	private class HoldListener implements OnClickListener {

		@Override
		public void onClick(View v) {


			EasyTracker.getTracker().sendEvent("Search", "Place Hold Button Pressed", null, null);
			SharedPreferences prefs = getSharedPreferences("myPrefs",
					Context.MODE_WORLD_WRITEABLE);
			boolean loggedIn = prefs.getBoolean("loggedIn", false);
			if (loggedIn) {
				showHoldDialog();
			} else {
				Intent intent = new Intent(v.getContext(), LoginActivity.class);
				intent.putExtra("destination", "placeHold");
				startActivityForResult(intent, LOGIN);
			}

		}

	}

	private class MoreAuthorListener implements OnClickListener {

		@Override
		public void onClick(View view) {
			
			
			Mobile_ACPL app = (Mobile_ACPL)thisActivity.getApplication();
			EasyTracker.getTracker().sendEvent("Search", "More By Author Button Pressed", null, null);

			findViewById(R.id.moreAuthorBar).setVisibility(View.VISIBLE);
			String author = getIntent().getStringExtra("author");
			MoreAuthorSearchHandler handler = new MoreAuthorSearchHandler(
					thisActivity);

			app.setAuthorSearchHandler(handler);

			handler.search(author, SearchCatalogHandler.RESULTS_PER_PAGE,
					"author", null, null);

		}

	}

	private class ImageListener implements OnClickListener {

		@Override
		public void onClick(View arg0) {
			Intent newIntent = new Intent(thisActivity,
					LargeCoverActivity.class);
			String isbn = getIntent().getStringArrayExtra("isbn")[0];
			newIntent.putExtra("isbn", isbn);
			startActivity(newIntent);

		}

	}

	private class OverdriveListener implements OnClickListener {

		@Override
		public void onClick(View view) {

			EasyTracker.getTracker().sendEvent("Search", "Overdrive Button Pressed", null, null);
			
			findViewById(R.id.overdriveBar).setVisibility(View.VISIBLE);
			String url = getIntent().getStringExtra("url");
			Uri uri = Uri.parse(url);
			Intent intent = new Intent(Intent.ACTION_VIEW, uri);
			startActivity(intent);
		}

	}
	
	private class AddToListListener implements OnClickListener {

		@Override
		public void onClick(View view) {

			EasyTracker.getTracker().sendEvent("Lists", "Add to Lists pressed", null, null);

			Intent intent = new Intent(view.getContext(), MyListsAddActivity_.class);
			intent.putExtra("titleID",titleID);
			intent.putExtra("title", title);
			intent.putExtra("author", author);
			intent.putExtra("isbn", isbn);
			intent.putExtra("holdable", holdable);
			intent.putExtra("yearOfPublications", yearOfPublication);
			startActivity(intent);
		}

	}


	@Override
	public void onResume() {
		super.onResume();
		findViewById(R.id.moreAuthorBar).setVisibility(View.GONE);
		findViewById(R.id.overdriveBar).setVisibility(View.GONE);
		

		
	}
}
